<template>
  <div class="p-4">
    <Card title="店铺标品管理">
      <template #extra>
        <Space>
          <Button type="primary" @click="openCategoryModal">分类管理</Button>
          <Button type="primary" @click="showModal = true">新增商品</Button>
        </Space>
      </template>
      <div class="text-gray-500 mb-4">支持商品录入、修改、删除等操作。</div>

      <!-- 顶部搜索 -->
      <div class="mb-4 flex gap-3">
        <Input v-model:value="searchName" placeholder="请输入商品名称" style="width: 240px" />
        <Select v-model:value="searchLevel1" :options="level1Opts" placeholder="请选择一级类目" style="width: 160px" allowClear />
        <Select v-model:value="searchLevel2" :options="level2Opts" placeholder="请选择二级类目" style="width: 160px" allowClear :disabled="!searchLevel1" />
        <Button @click="resetSearch">重置</Button>
      </div>

      <!-- 商品表格 -->
      <Table :columns="columns" :data-source="filteredList" :pagination="false" row-key="id" />
    </Card>

    <!-- 分类管理弹窗 -->
    <Modal v-model:visible="showCategoryModal" title="分类管理" width="700px" @cancel="resetCategoryForm">
      <div class="flex">
        <div class="w-1/2 pr-4 border-r">
          <Tree :tree-data="categories" :expanded-keys="expandedKeys" v-model:selectedKeys="selectedKeys" @select="onSelectCategory" @expand="onExpand">
            <template #title="{ key, title }">
              <div class="flex items-center justify-between w-full">
                <span>{{ title }}</span>
                <Button type="link" size="small" @click.stop="handleDeleteCategory(key)">删除</Button>
              </div>
            </template>
          </Tree>
        </div>
        <div class="w-1/2 pl-4">
          <Form layout="vertical">
            <Form.Item label="分类名称" required>
              <Input v-model:value="categoryForm.name" placeholder="请输入分类名称" />
            </Form.Item>
            <Form.Item v-if="!categoryEditMode" label="父级分类">
              <Select v-model:value="categoryForm.parentId" placeholder="不选择则创建一级分类" allowClear>
                <Select.Option v-for="item in categories" :key="item.key" :value="item.key">{{ item.title }}</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" @click="categoryEditMode ? editCategory() : (categoryForm.parentId ? addSubCategory() : addRootCategory())">
                  {{ categoryEditMode ? '保存修改' : '添加分类' }}
                </Button>
                <Button v-if="categoryEditMode" @click="resetCategoryForm">取消编辑</Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
      </div>
    </Modal>

    <!-- 新增/编辑商品弹窗 -->
    <Modal v-model:open="showModal" :title="modalTitle" :confirm-loading="saving" width="600px" @ok="handleSubmit" @cancel="resetAddForm">
      <Form :model="addForm" :rules="rules" layout="horizontal" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <Form.Item name="name" label="商品名称" :rules="rules.name">
          <Input v-model:value="addForm.name" placeholder="请输入商品名称" />
        </Form.Item>
        <Form.Item name="firstCategory" label="一级分类" :rules="[{ required: true, message: '请选择一级分类' }]">
          <Select v-model:value="addForm.firstCategory" placeholder="请选择一级分类" :options="firstCategoryOpts" allowClear />
        </Form.Item>
        <Form.Item name="secondCategory" label="二级分类" :rules="[{ required: true, message: '请选择二级分类' }]">
          <Select v-model:value="addForm.secondCategory" placeholder="请选择二级分类" :options="secondCategoryOpts" allowClear :disabled="!addForm.firstCategory" />
        </Form.Item>
        <Form.Item name="singlePrice" label="单瓶价(元)" :rules="rules.singlePrice">
          <InputNumber v-model:value="addForm.singlePrice" :min="0" :precision="2" style="width: 100%" placeholder="请输入单瓶价" />
        </Form.Item>
        <Form.Item name="boxPrice" label="原箱价(元)" :rules="rules.boxPrice">
          <InputNumber v-model:value="addForm.boxPrice" :min="0" :precision="2" style="width: 100%" placeholder="请输入原箱价" />
        </Form.Item>
        <Form.Item name="recyclePrice" label="回收价(元)" :rules="rules.recyclePrice">
          <InputNumber v-model:value="addForm.recyclePrice" :min="0" :precision="2" style="width: 100%" placeholder="请输入回收价" />
        </Form.Item>
        <Form.Item label="商品图片">
          <Upload
            v-model:fileList="fileList"
            list-type="picture-card"
            :customRequest="handleUpload"
            :remove="handleRemove"
          >
            <div>选择图片</div>
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, reactive, watch, h } from 'vue'
import { getProductList, addProduct, updateProduct, deleteProduct, getCategoryTree, addCategory, updateCategory, deleteCategory, uploadFile } from '#/api'
import { Button, Card, Form, Input, InputNumber, Modal, Select, Table, Upload, message, Space, Tree } from 'ant-design-vue'

void [Button, Card, Form, Input, InputNumber, Modal, Select, Table, Upload, Space, Tree]

// 搜索
const searchName = ref('')
const searchLevel1 = ref('')
const searchLevel2 = ref('')

// 分类树 & 一级下拉
const categories = ref<any[]>([])
const level1Opts = computed(() => [{ label: '全部', value: '' }, ...categories.value.map(n => ({ label: n.title, value: n.title }))])
const level2Opts = computed(() => {
  if (!searchLevel1.value) return []
  const node = categories.value.find(n => n.title === searchLevel1.value)
  return (node?.children || []).map((c: any) => ({ label: c.title, value: c.title }))
})

// 原始商品数据
const rawList = ref<any[]>([])

// 过滤列表
const filteredList = computed(() =>
  rawList.value.filter((p: any) => {
    const nameMatch = !searchName.value || p.name.toLowerCase().includes(searchName.value.toLowerCase())
    const l1Match = !searchLevel1.value || p.firstCategory === searchLevel1.value
    const l2Match = !searchLevel2.value || p.secondCategory === searchLevel2.value
    return nameMatch && l1Match && l2Match
  })
)

// 表格列
const columns = [
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '一级分类', dataIndex: 'firstCategory', key: 'firstCategory' },
  { title: '二级分类', dataIndex: 'secondCategory', key: 'secondCategory' },
  { title: '单瓶价(元)', dataIndex: 'singleBottleSellingPrice', key: 'singleBottleSellingPrice' },
  { title: '原箱价(元)', dataIndex: 'originalBoxSellingPrice', key: 'originalBoxSellingPrice' },
  { title: '回收价(元)', dataIndex: 'singleBottleRecyclingPrice', key: 'singleBottleRecyclingPrice' },
  { title: '状态', dataIndex: 'statusName', key: 'statusName' },
  {
    title: '操作',
    key: 'action',
    customRender: ({ record }: any) =>
      h(Space, [
        h(Button, { type: 'link', size: 'small', icon: h('i', { class: 'i-carbon:edit' }), onClick: () => handleEdit(record) }, '编辑'),
        h(Button, { type: 'link', size: 'small', danger: true, icon: h('i', { class: 'i-carbon:trash-can' }), onClick: () => handleDelete(record) }, '删除')
      ])
  }
]

// 弹窗控制
const showModal = ref(false)
const showCategoryModal = ref(false)
const saving = ref(false)
const isEdit = ref(false)
const modalTitle = computed(() => (isEdit.value ? '编辑商品' : '新增商品'))

const addForm = reactive({
  name: '',
  firstCategory: '',
  secondCategory: '',
  singlePrice: null as number | null,
  boxPrice: null as number | null,
  recyclePrice: null as number | null
})

const fileList = ref<any[]>([])

const rules = {
  name: [{ required: true, message: '请输入商品名称' }],
  category: [{ required: true, message: '请选择商品分类' }],
  singlePrice: [{ required: true, message: '请输入单瓶价' }],
  boxPrice: [{ required: true, message: '请输入原箱价' }],
  recyclePrice: [{ required: true, message: '请输入回收价' }]
}

// 分类管理
const categoryForm = reactive({ parentId: null as string | null, name: '' })
const categoryEditMode = ref(false)
const currentCategoryKey = ref<string | null>(null)
const expandedKeys = ref<string[]>([])
const selectedKeys = ref<string[]>([])

const firstCategoryOpts = computed(() => categories.value.map((c: any) => ({ label: c.title, value: c.title })))
const secondCategoryOpts = computed(() => {
  if (!addForm.firstCategory) return []
  const node = categories.value.find((n: any) => n.title === addForm.firstCategory)
  return (node?.children || []).map((c: any) => ({ label: c.title, value: c.title }))
})

// 方法
function resetSearch() {
  searchName.value = ''
  searchLevel1.value = ''
  searchLevel2.value = ''
}

function resetAddForm() {
  Object.assign(addForm, { name: '', firstCategory: '', secondCategory: '', singlePrice: null, boxPrice: null, recyclePrice: null })
  fileList.value = []
  isEdit.value = false
}

// 上传
async function handleUpload({ file, onSuccess, onError }: any) {
  try {
    const res = await uploadFile(file)
    // 后端返回的地址在 message 字段
    onSuccess(res?.message || '')
  } catch {
    onError(new Error('上传失败'))
  }
}

function handleRemove(file: any) {
  const index = fileList.value.indexOf(file)
  if (index > -1) fileList.value.splice(index, 1)
}

const currentEditId = ref<string | null>(null)

function handleEdit(record: any) {
  currentEditId.value = record.id
  Object.assign(addForm, { name: record.name, firstCategory: record.firstCategory, secondCategory: record.secondCategory, singlePrice: record.singleBottleSellingPrice, boxPrice: record.originalBoxSellingPrice, recyclePrice: record.singleBottleRecyclingPrice })
  // 回显已有图片
  fileList.value = (record.image || []).map((url: string, idx: number) => ({ uid: idx, url, status: 'done' }))
  isEdit.value = true
  showModal.value = true
}

async function handleDelete(record: any) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除商品“${record.name}”吗？`,
    async onOk() {
      try {
        await deleteProduct(record.id)
        message.success('删除成功')
        // 重新拉最新列表
        const res = await getProductList()
        rawList.value = Array.isArray(res) ? res : (res?.data || [])
      } catch {
        message.error('删除失败')
      }
    }
  })
}

async function handleSubmit() {
  if (!addForm.name || !addForm.firstCategory || !addForm.secondCategory || addForm.singlePrice == null || addForm.boxPrice == null || addForm.recyclePrice == null) {
    message.error('请完善表单信息')
    return
  }
  saving.value = true
  const payload = {
    name: addForm.name.trim(),
    firstCategory: addForm.firstCategory,
    secondCategory: addForm.secondCategory,
    singleBottleSellingPrice: Number(addForm.singlePrice),
    originalBoxSellingPrice: Number(addForm.boxPrice),
    singleBottleRecyclingPrice: Number(addForm.recyclePrice),
    originalBoxRecyclingPrice: Number(addForm.recyclePrice), // 后端需要字段
    status: 1,
    image: fileList.value.map((f: any) => f.response || f.url || '')
  }
  try {
    if (isEdit.value) {
      // 编辑：调真实接口
      await updateProduct({ ...payload, id: currentEditId.value! })
      message.success('编辑商品成功')
    } else {
      // 新增：调接口
      await addProduct(payload)
      message.success('新增商品成功')
    }
    // 重新拉最新列表
    const res = await getProductList()
    rawList.value = Array.isArray(res) ? res : (res?.data || [])
    showModal.value = false
    resetAddForm()
  } catch {
    message.error('保存失败')
  } finally {
    saving.value = false
  }
}

async function openCategoryModal() {
  try {
    const res = await getCategoryTree()
    const list = Array.isArray(res) ? res : (res?.data || [])
    categories.value = list.map((node: any) => ({
      key: node.id,
      title: node.name,
      children: (node.children || []).map((c: any) => ({ key: c.id, title: c.name, children: c.children || [] }))
    }))
    expandedKeys.value = categories.value.map(n => n.key)
  } catch {
    message.error('获取分类失败')
  }
  showCategoryModal.value = true
  resetCategoryForm()
}

function resetCategoryForm() {
  categoryForm.parentId = null
  categoryForm.name = ''
  categoryEditMode.value = false
  currentCategoryKey.value = null
}

function onExpand(keys: string[]) {
  expandedKeys.value = keys
}

function onSelectCategory(keys: string[], { node }: any) {
  if (!keys.length) return
  currentCategoryKey.value = keys[0]
  categoryEditMode.value = true
  categoryForm.name = node.title
  categoryForm.parentId = node.parentKey || null
}

async function addRootCategory() {
  if (!categoryForm.name.trim()) return message.error('请输入分类名称')
  try {
    await addCategory({ name: categoryForm.name.trim(), parentId: '0' })
    message.success('添加一级分类成功')
    await openCategoryModal()
  } catch {
    message.error('添加失败')
  }
  resetCategoryForm()
}

async function addSubCategory() {
  if (!categoryForm.parentId) return message.error('请选择父级分类')
  if (!categoryForm.name.trim()) return message.error('请输入分类名称')
  try {
    await addCategory({ name: categoryForm.name.trim(), parentId: categoryForm.parentId })
    message.success('添加二级分类成功')
    await openCategoryModal()
    expandedKeys.value = Array.from(new Set([...expandedKeys.value, categoryForm.parentId]))
  } catch {
    message.error('添加失败')
  }
  resetCategoryForm()
}

async function editCategory() {
  if (!currentCategoryKey.value) return message.error('请选择要编辑的分类')
  if (!categoryForm.name.trim()) return message.error('请输入分类名称')
  try {
    await updateCategory({ id: currentCategoryKey.value, name: categoryForm.name.trim() })
    message.success('编辑分类成功')
    await openCategoryModal()
  } catch {
    message.error('编辑失败')
  }
  resetCategoryForm()
}

async function handleDeleteCategory(key: string) {
  Modal.confirm({
    title: '确认删除',
    content: '删除后不可恢复，是否继续？',
    async onOk() {
      try {
        await deleteCategory(key)
        message.success('删除分类成功')
        await openCategoryModal()
      } catch {
        message.error('删除失败')
      }
    }
  })
}

// 初始化
import { onMounted } from 'vue'

onMounted(async () => {
  // 先拉分类，再拉商品
  try {
    const cRes = await getCategoryTree()
    const cList = Array.isArray(cRes) ? cRes : (cRes?.data || [])
    categories.value = cList.map((node: any) => ({
      key: node.id,
      title: node.name,
      children: (node.children || []).map((c: any) => ({ key: c.id, title: c.name, children: c.children || [] }))
    }))
  } catch {
    message.error('获取分类失败')
  }

  try {
    const res = await getProductList()
    const list = Array.isArray(res) ? res : (res?.data || [])
    rawList.value = list
  } catch {
    message.error('获取商品列表失败')
  }
})

watch(searchLevel1, () => { searchLevel2.value = '' })
// 新增弹窗一级清空时同步清空二级
watch(() => addForm.firstCategory, (val) => { if (!val) addForm.secondCategory = '' })
</script>
